import React from 'react';
import { message } from 'antd';
import { Redirect, connect, ConnectProps, Dispatch } from 'umi';
import { stringify } from 'querystring';
import { PageLoading } from '@ant-design/pro-layout';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import { getCurrentLoginUserId, getRoutes } from '@/utils/authority';

interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  dispatch: Dispatch;
  queryMenuLoading: boolean;
}

interface SecurityLayoutState {
  isReady: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
  };

  componentDidMount() {
    // this.setState({
    //   isReady: true,
    // });
    // const { dispatch } = this.props;
    // if (dispatch) {
    //   dispatch({
    //     type: 'user/fetchCurrent',
    //   });
    // }
    const userId = getCurrentLoginUserId();
    console.info('SecurityLayout.componentDidMount', userId);
    if (userId) {
      // 用户已存在，则查询菜单
      // 查询用户菜单信息，用户登录即查询
      const { dispatch } = this.props;
      dispatch({
        type: 'menu/getMenuData',
        payload: {
          userId
        }
      });
    }
  }

  render() {
    console.info('SecurityLayout.render');
    const { isReady } = this.state;
    const { children, loading, currentUser, queryMenuLoading } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    console.info(currentUser);
    const userId = getCurrentLoginUserId();
    const pathUrl = window.location.pathname;
    const protocol = window.location.protocol;
    const host = window.location.host;
    // http://localhost:8000/
    const urlStr = `${protocol}//${host}/`;
    let queryString;
    if (urlStr !== window.location.href) {
      queryString = stringify({
        redirect: window.location.href,
      });
    }
    console.info(queryString);
    console.info(pathUrl);
    const routes = getRoutes();
    console.info(routes);
    if(routes && pathUrl !== '/user/login' && routes.indexOf(pathUrl) < 0) {
      if (pathUrl !== '/welcome') {
        console.info('非法访问', pathUrl);
        message.warning('请勿访问未经授权的页面');
        return <Redirect to={`/user/login`} />;
      }
    }
    // 没有登录，查询还没返回，显示正在加载
    // 菜单查询没有返回，也要显示正在加载
    console.info('SecurityLayout--11', !userId, loading, queryMenuLoading);
    if ((!userId && loading) || queryMenuLoading) {
      return <PageLoading />;
    }
    // 用户id为空，并且当前页面非登录页面，则跳转至登录页面
    if (!userId && pathUrl !== '/user/login') {
      console.info('跳转至登录ing');
      if (queryString) {
        console.info('跳转至登录ing2');
        return <Redirect to={`/user/login?${queryString}`} />;
      }
      console.info('跳转至登录ing3');
      return <Redirect to={`/user/login`} />;
    }
    return children;
  }
}

export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  queryMenuLoading: loading.effects['menu/getMenuData'],
}))(SecurityLayout);